package com.gjd.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gjd.config.AlipayConfig;
import com.gjd.domain.ResponseResult;
import com.gjd.domain.dto.OrderdDto;
import com.gjd.domain.entity.Category;
import com.gjd.domain.entity.Orders;
import com.gjd.domain.entity.ServerCondition;
import com.gjd.domain.entity.User;
import com.gjd.domain.vo.OrderInfo;
import com.gjd.domain.vo.PageVo;
import com.gjd.domain.vo.enums.AppHttpCodeEnum;
import com.gjd.mapper.CategoryMapper;
import com.gjd.mapper.ServerConditionMapper;
import com.gjd.mapper.UserMapper;
import com.gjd.service.OrdersService;
import com.gjd.mapper.OrdersMapper;
import com.gjd.utils.BeanCopyUtils;
import com.gjd.utils.SecurityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.jupiter.api.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yang'shun'tao
 * @description 针对表【orders(订单表)】的数据库操作Service实现
 * @createDate 2023-01-16 21:39:20
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
        implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private ServerConditionMapper serverConditionMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public ResponseResult cancelOrder(Long orderId) {
//        调用支付宝提供的统一收单交易关闭接口
        try {
            this.closeOrder(orderId);
        } catch (JSONException e) {
            return ResponseResult.errorResult(611, "取消失败");
        } catch (AlipayApiException e) {
            return ResponseResult.errorResult(611, "取消失败");
        }
//        更新用户订单状态
        Orders orders = new Orders();
        orders.setId(orderId);
        orders.setStatus("已取消");
        ordersMapper.updateById(orders);
        return ResponseResult.okResult();
    }

    private void closeOrder(Long orderId) throws JSONException, AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, "json", "GBK", AlipayConfig.ALIPAY_PUBLIC_KEY, "RSA2");
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }

    @Override
    public ResponseResult createOrder(OrderInfo orderInfo) {
//        Orders orders = new Orders();
//        orders.setUserId(orderInfo.getu);
//        orders.setServerId();
//        ordersMapper.insert(orders);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult createOrder(OrderdDto orderdDto) {
        Orders order = BeanCopyUtils.copyBean(orderdDto, Orders.class);
        order.setUserId(SecurityUtils.getUserId());
        ordersMapper.insert(order);
        return ResponseResult.okResult();

    }

    @Override
    public ResponseResult getUserOrder(String orderStatus, Long pageNum, Long pageSize) {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ServerCondition> serverConditionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId, userId);
        if (!orderStatus.equals("全部")){
            ordersLambdaQueryWrapper.eq(Orders::getStatus, orderStatus);
        }
        Page<Orders> page = new Page<>(pageNum, pageSize);
        List<Orders> ordersList = page(page, ordersLambdaQueryWrapper).getRecords();
        List<OrderInfo> orderInfoList = BeanCopyUtils.copyBeanList(ordersList, OrderInfo.class);
        for (int i = 0; i < orderInfoList.size(); i++) {
            Long serverId = orderInfoList.get(i).getServerId();
            serverConditionLambdaQueryWrapper.eq(ServerCondition::getServerId,serverId);
            ServerCondition serverCondition = serverConditionMapper.selectOne(serverConditionLambdaQueryWrapper);
            categoryLambdaQueryWrapper.eq(Category::getId,serverCondition.getCategoryId());
            String categoryName = categoryMapper.selectOne(categoryLambdaQueryWrapper).getName();
            userLambdaQueryWrapper.eq(User::getId,serverId);
            User server = userMapper.selectOne(userLambdaQueryWrapper);
            orderInfoList.get(i).setServerName(server.getNickName());
            orderInfoList.get(i).setServerType(serverCondition.getServerType());
            orderInfoList.get(i).setServerPhone(serverCondition.getPhone());
            orderInfoList.get(i).setCategoryName(categoryName);
            orderInfoList.get(i).setServerArea(serverCondition.getServerArea());
            orderInfoList.get(i).setTreatment(serverCondition.getTreatment());
        }
        PageVo pageVo = new PageVo(orderInfoList, (long) orderInfoList.size());
        return ResponseResult.okResult(pageVo);
    }

    /**
     *
     * @param orderStatus
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseResult getServerOrder(String orderStatus, Long pageNum, Long pageSize) {
        Long serverId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ServerCondition> serverConditionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getServerId, serverId);
        if (!orderStatus.equals("全部")) {
            ordersLambdaQueryWrapper.eq(Orders::getStatus, orderStatus);
        }
        Page<Orders> page = new Page<>(pageNum, pageSize);
        List<Orders> ordersList = page(page, ordersLambdaQueryWrapper).getRecords();
        List<OrderInfo> orderInfoList = BeanCopyUtils.copyBeanList(ordersList, OrderInfo.class);
        for (int i = 0; i < orderInfoList.size(); i++) {
            // TODO:当出现家政人员服务为不同人服务多个单时，会造成查询错乱，是否应该利用serverId进行查询
            serverConditionLambdaQueryWrapper.eq(ServerCondition::getServerId,serverId);
            ServerCondition serverCondition = serverConditionMapper.selectOne(serverConditionLambdaQueryWrapper);
            categoryLambdaQueryWrapper.eq(Category::getId,serverCondition.getCategoryId());
            String categoryName = categoryMapper.selectOne(categoryLambdaQueryWrapper).getName();
            userLambdaQueryWrapper.eq(User::getId,serverId);
            User user = userMapper.selectOne(userLambdaQueryWrapper);
            orderInfoList.get(i).setUserName(user.getNickName());
            orderInfoList.get(i).setArea(user.getArea());
            orderInfoList.get(i).setCategoryName(categoryName);
            orderInfoList.get(i).setUserPhone(serverCondition.getPhone());
            orderInfoList.get(i).setTreatment(serverCondition.getTreatment());
        }
        PageVo pageVo = new PageVo(orderInfoList, (long) orderInfoList.size());
        return ResponseResult.okResult(pageVo);
    }

}




